package com.dushuren.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dushuren.project.common.ErrorCode;
import com.dushuren.project.exception.BusinessException;
import com.dushuren.project.mapper.TeamApplyMapper;
import com.dushuren.project.mapper.TeamMapper;
import com.dushuren.project.mapper.UserTeamMapper;
import com.dushuren.project.model.dto.*;
import com.dushuren.project.model.entity.Team;
import com.dushuren.project.model.entity.TeamApply;
import com.dushuren.project.model.vo.TeamApplyVo;
import com.dushuren.project.service.TeamApplyService;
import com.dushuren.project.service.TeamService;
import com.dushuren.project.service.UserService;
import com.dushuren.project.service.UserTeamService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;
import java.util.stream.Collectors;

import static com.dushuren.project.constant.TeamApplyConstant.*;

/**
* @author qieqie
* @description 针对表【team_apply(队伍申请管理)】的数据库操作Service实现
* @createDate 2022-10-19 18:40:21
*/
@Service
public class TeamApplyServiceImpl extends ServiceImpl<TeamApplyMapper, TeamApply>
    implements TeamApplyService {

  @Resource
  UserTeamMapper userTeamMapper;

  @Resource
  TeamApplyMapper teamApplyMapper;

  @Resource
  TeamService teamService;

  @Resource
  TeamMapper teamMapper;

  @Resource
  UserTeamService userTeamService;


  @Resource
  UserService userService;

  @Override
  public Boolean applyJoinTeam(ApplyJoinTeamRequest applyJoinTeamRequest) {
	//1. 校验申请者
	//   1. 申请者，加入队伍的数量是否   >= 5队伍
	Long userId = applyJoinTeamRequest.getUserId();
	userTeamService.QueryUserTeam(userId);
	// 校验 申请队伍的数量 《= 5
	Long aLong = applyTeamNum(userId);
	//2. 校验申请队伍信息
	//   1. 队伍id
	Long teamId = applyJoinTeamRequest.getTeamId();
	if (teamId <= 0) {
	  throw new BusinessException(ErrorCode.PARAMS_ERROR);
	}
	// 1. 队伍id是否存在，队伍的人数是否已满 需要查询队伍的最大人数 、 查询队伍现在已有多少人数
	Long resultAmount = teamService.teamWantingAmount(teamId);
	if (resultAmount == 0) {
	  throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍已加满");
	}
	//   3. 申请内容
	// todo 之后需要对里面的关键字进行 审核

	//      1. 申请内容是否在
	String applyContent = applyJoinTeamRequest.getApplyContent();
	if (applyContent == null || applyContent.length() > TEAM_APPLY_CONTEXT ) {
	  throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不符合条件");
	}
	//3. 写入 teamApply表中
	TeamApply teamApply = new TeamApply();
	BeanUtils.copyProperties(applyJoinTeamRequest, teamApply);
	boolean save = this.save(teamApply);
	if (!save) {
	  throw new BusinessException(ErrorCode.SYSTEM_ERROR);
	}
	return true;
  }


  @Override
  public Boolean applyDeleteTeam(ApplyDeleteTeamRequest applyDeleteTeamRequest) {
	QueryWrapper<TeamApply> queryWrapper = new QueryWrapper<>();
	Long id = applyDeleteTeamRequest.getId();
	queryWrapper.select("id");
	queryWrapper.eq("id",id);
	Long resultCount = teamApplyMapper.selectCount(queryWrapper);
	if (resultCount == null || resultCount == 0) {
	  throw new BusinessException(ErrorCode.PARAMS_ERROR);
	}
	boolean remove = this.remove(queryWrapper);
	if (!remove) {
	  throw new BusinessException(ErrorCode.SYSTEM_ERROR);
	}
	return true;
  }

  @Override
  public Boolean applyDeleteTeam(Long teamId, Long userId) {
	QueryWrapper<TeamApply> queryWrapper = new QueryWrapper<>();
	queryWrapper.select("id");
	queryWrapper.eq("teamId", teamId);
	queryWrapper.eq("userId", userId);
	boolean resultRemove = this.remove(queryWrapper);
	return resultRemove;
  }

  @Override
  public List<TeamApplyVo> listQueryApplyTeam(ApplyListQueryTeamRequest listQueryTeam) {
	QueryWrapper<TeamApply> queryWrapper = new QueryWrapper<>();
	queryWrapper.select("id", "teamId", "userId", "applyContent", "applyReviewStatus", "applyReviewMessage", "createTime");
	Long id = listQueryTeam.getId();
	if (id != null) {
	  queryWrapper.eq("id", id);
	}
	Long teamId = listQueryTeam.getTeamId();
	if (teamId != null) {
	  queryWrapper.eq("teamId", teamId);
	}
	Long userId = listQueryTeam.getUserId();
	if (userId != null) {
	  queryWrapper.eq("userId", userId);
	}
	String applyContent = listQueryTeam.getApplyContent();
	if (StringUtils.isNotBlank(applyContent)) {
	  queryWrapper.eq("applyContent", applyContent);
	}
	String applyReviewMessage = listQueryTeam.getApplyReviewMessage();
	if (StringUtils.isNotBlank(applyReviewMessage)) {
	  queryWrapper.eq("applyReviewMessage", applyReviewMessage);
	}
	if (TEAM_APPLY_STATE_IN.equals(listQueryTeam.getApplyReviewStatus())) {
	  queryWrapper.eq("applyReviewStatus", TEAM_APPLY_STATE_IN);
	} else if (TEAM_APPLY_STATE_ADOPT.equals(listQueryTeam.getApplyReviewStatus())) {
	  queryWrapper.eq("applyReviewStatus", TEAM_APPLY_STATE_ADOPT);
	} else if (TEAM_APPLY_STATE_REFUSE.equals(listQueryTeam.getApplyReviewStatus())) {
	  queryWrapper.eq("applyReviewStatus", TEAM_APPLY_STATE_REFUSE);
	}

	return teamApplyMapper.selectList(queryWrapper).stream().map(teamApply -> {
	  TeamApplyVo teamApplyVo = new TeamApplyVo();
	  BeanUtils.copyProperties(teamApply, teamApplyVo);
	  return teamApplyVo;
	}).collect(Collectors.toList());
  }

  /**
   *  队长查看当前申请列表
   */
  @Override
  public List<TeamApplyVo> captainGetApplyTeam(ApplyCaptainGetTeamRequest captainGetTeam) {
	QueryWrapper<Team> queryWrapperTeam = new QueryWrapper<>();
	QueryWrapper<TeamApply> queryWrapperTeamApply = new QueryWrapper<>();
	queryWrapperTeamApply.select("id", "teamId", "userId", "applyContent", "applyReviewStatus", "applyReviewMessage", "createTime");
	queryWrapperTeamApply.eq("applyReviewStatus", TEAM_APPLY_STATE_IN);
	queryWrapperTeam.select("id");
	queryWrapperTeam.eq("userId",captainGetTeam.getUserId());
	// todo 这里之后如果需要将 队伍名名称一并返回时在进行修改
	// Map<Long, List<Team>> resultTeam = teamMapper.selectList(queryWrapperTeam).stream().collect(Collectors.groupingBy(Team::getId));
	List<Long> resultTeamId = teamMapper.selectList(queryWrapperTeam).stream().map(Team::getId).collect(Collectors.toList());
	if (resultTeamId.isEmpty()) {
	  throw new BusinessException(ErrorCode.PARAMS_ERROR);
	}
	Long teamId = captainGetTeam.getTeamId();
	if (teamId != null) {
	  queryWrapperTeamApply.eq("teamId", teamId);
	} else {
	  queryWrapperTeamApply.in("teamId",resultTeamId);
	}
	UserGetRequest userGetRequest = new UserGetRequest();
	return teamApplyMapper.selectList(queryWrapperTeamApply).stream().map(teamApply -> {
	  TeamApplyVo teamApplyVo = new TeamApplyVo();
	  BeanUtils.copyProperties(teamApply, teamApplyVo);
	  userGetRequest.setId(teamApplyVo.getUserId());
	  teamApplyVo.setUserVo(userService.getSftUser(userService.getUser(userGetRequest)));
	  return teamApplyVo;
	}).collect(Collectors.toList());
  }


  /***
   * 校验是否反复申请同一个队伍 申请过 true 没申请过false
   * @param teamId
   * @param userId
   * @return
   */
  @Override
  public Boolean checkApplyTeam(Long teamId, Long userId) {
	QueryWrapper<TeamApply> queryWrapperTeamApply = new QueryWrapper<>();
	queryWrapperTeamApply.select("id");
	queryWrapperTeamApply.eq("teamId", teamId);
	queryWrapperTeamApply.eq("userId", userId);
	Long count1 = teamApplyMapper.selectCount(queryWrapperTeamApply);
	return count1 > 0;
  }

  /***
   * 校验是否为队伍队长 ，是true 不是false
   * @param teamId
   * @param userId
   * @return
   */
  @Override
  public Boolean checkCapatinTeam(Long teamId, Long userId) {
	QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
	queryWrapper.select("id");
	queryWrapper.eq("id", teamId);
	queryWrapper.eq("userId", userId);
	Long count = teamMapper.selectCount(queryWrapper);
	return count == 1;
  }

  /**
   * 校验 申请加入队伍的数量是否 超出 5条
   */
  @Override
  public Long applyTeamNum(Long userId) {
	QueryWrapper<TeamApply> queryWrapperTeamApply = new QueryWrapper<>();
	queryWrapperTeamApply.select("id");
	//   2.  申请者，申请的数量是否 < 5 条 （只查询还在审核中的）
	queryWrapperTeamApply.eq("userId", userId);
	queryWrapperTeamApply.eq("applyReviewStatus", TEAM_APPLY_STATE_IN);
	Long applyCount = teamApplyMapper.selectCount(queryWrapperTeamApply);
	if (applyCount >= TEAM_APPLY_MAS_COUNT) {
	  throw new BusinessException(ErrorCode.PARAMS_ERROR,"队伍申请数量已满");
	}
	return applyCount;
  }


  /***
   *校验 申请加入队伍的 id 是否存在  状态自定义
   */
  @Override
  public Boolean isApplyTeamId(Long id, Integer status) {
	if (id <= 0) {
	  throw new BusinessException(ErrorCode.SYSTEM_ERROR);
	}
	QueryWrapper<TeamApply> queryWrapper = new QueryWrapper<>();
	queryWrapper.select("id");
	queryWrapper.eq("id", id);
	queryWrapper.eq("applyReviewStatus", status);
	Long count = teamApplyMapper.selectCount(queryWrapper);
	return count != 1;
  }
}




